package com.usian.service.impl;

import com.usian.mapper.TbItemCatMapper;
import com.usian.pojo.TbItemCat;
import com.usian.pojo.TbItemCatExample;
import com.usian.redis.RedisClient;
import com.usian.service.ItemCategoryService;
import com.usian.utils.CatNode;
import com.usian.utils.CatResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class ItemCategoryServiceImpl implements ItemCategoryService {

    @Autowired
    TbItemCatMapper tbItemCatMapper;

    @Autowired
    RedisClient redisClient;

    @Value("${PROTAL_CATRESULT_KEY}")
    private String PROTAL_CATRESULT_KEY;

    /**
     * 左边框分类
     *
     * @return
     */
    @Override
    public CatResult selectItemCategoryAll() {
        CatResult catResult = (CatResult) redisClient.get(PROTAL_CATRESULT_KEY);
        if (catResult != null){
            return catResult;
        }
        catResult = new CatResult();
        //查询完数据存储到catResult中返回数据
        catResult.setData(getCatList(0L));
        redisClient.set(PROTAL_CATRESULT_KEY, catResult);
        return catResult;
    }
    //由selectItemCategoryAll调用的一个方法接收参数默认为0
    private List<?> getCatList(Long parentId){
        //创建查询条件
        TbItemCatExample example = new TbItemCatExample();
        TbItemCatExample.Criteria criteria = example.createCriteria();
        criteria.andParentIdEqualTo(parentId);
        //查询到对应子节点的数据
        List<TbItemCat> list = this.tbItemCatMapper.selectByExample(example);
        List resultList = new ArrayList();
        int count = 0;
        //遍历集合存储对应返回的数据结构
        for(TbItemCat tbItemCat:list){
            //判断是否是父节点，如果是父级分类会继续查询父类下的子分类
            if(tbItemCat.getIsParent()){
                CatNode catNode = new CatNode();
                //对应分类的名称
                catNode.setName(tbItemCat.getName());
                //递归getCatList查询该分类名称下的子节点存入catNode对应list属性中
                catNode.setItem(getCatList(tbItemCat.getId()));
                //查到所有的分类父子级数据后放入list集合中
                resultList.add(catNode);
                count++;
                //只取商品分类中的 18 条数据
                if (count == 18){
                    break;
                }
            }else{
                //如果没有子分类就直接存如list
                resultList.add(tbItemCat.getName());
            }
        }
        return resultList;
    }

    @Override
    public List<TbItemCat> selectItemCategoryByParentId(Long id) {

        TbItemCatExample catExample = new TbItemCatExample();
        TbItemCatExample.Criteria criteria = catExample.createCriteria();
        criteria.andParentIdEqualTo(id);
        criteria.andStatusEqualTo(1);
        return tbItemCatMapper.selectByExample(catExample);
    }
}
